import { Form, Input, Button, Tabs, Message, Typography, Link, Spin } from '@arco-design/web-react';
import React, { useState, useMemo } from "react";
import { useNavigate } from 'react-router-dom'
import { IconPhone, IconUser } from '@arco-design/web-react/icon';
import { useDebounce } from "use-debounce"
import api from "../../API/loginApi";
import "@arco-design/web-react/dist/css/arco.css";
import './Login.css'
const TabPane = Tabs.TabPane;
const FormItem = Form.Item
const style = {
  textAlign: 'center',
  marginTop: 20,
};

// async () => {
//   try {
//     await form.validate();
//     Message.success('校验通过');
//   } catch (e) {
//     Message.error('校验失败');
//   }
// }
const Login = () => {
  // 路由信息
  const hitory = useNavigate()
  const [form] = Form.useForm();
  let [codeNum, setCodeNum] = useState('获取验证码')
  // 账号&&密码
  const [accountNum, setAccount] = useDebounce('')
  const [password, setPassword] = useState('')
  // 手机&&验证码
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  // 获取验证码
  const getCode = (target) => {
    async function exam () {
      try {
        await form.validate(['phone']);
        let num = 60;
        setCodeNum(num)
        let timer = setInterval(() => {
          num--
          if (num <= 0) {
            setCodeNum('获取验证码');
            clearInterval(timer)
            target.target.removeAttribute('disabled')
            target.target.style.backgroundColor = "#4080FF";
            target.target.style.cursor = "pointer";
          } else {
            setCodeNum(num)
          }
        }, 1000);
        target.target.setAttribute('disabled', 'disabled')
        target.target.style.backgroundColor = "#666";
        target.target.style.cursor = "not-allowed";
        // --------------------------获取验证码Api------------------------------
        api.getCode(phone).then(res => {
          console.log(res);
        })
      } catch (err) {
        console.log(err);
        Message.error('请输入正确的手机号码');
      }
    }
    exam();
  }
  // 手机号码登录
  const phoneLogin = () => {
    async function checkPhone () {
      try {
        await form.validate(['phone']);

        // --------------------------手机号登录Api------------------------------
        try {
          setLoading(true)
          await form.validate(['examCode']);
          console.log(code);
          api.phoneLogin(phone, code).then(res => {
            Message.success(res.msg)
            setLoading(false)
            // token
            sessionStorage.setItem('token', res.result.token)
            // 动态权限
            sessionStorage.setItem('navList', JSON.stringify(res.result.navlist))
            hitory('/home')
          })
        } catch (e) {
          Message.error('请输入验证码');
        }
      } catch (e) {
        Message.error('请输入手机号码');
      }
    }
    checkPhone();

  }
  // 账号密码登录
  const accountLogin = () => {
    async function checkAccount () {
      let phone = accountNum
      try {
        await form.validate(['account']);

        // --------------------------账号密码登录Api------------------------------
        try {
          await form.validate(['pwd']);
          setLoading(true)
          api.accountLogin(phone, password).then(res => {
            if (res.code === 200) {
              Message.success(res.msg)
              setLoading(false)
              // token
              sessionStorage.setItem('token', res.result.token)
              // 动态权限
              sessionStorage.setItem('navList', JSON.stringify(res.result.navlist))
              hitory('/home')
            }
            console.log(res);
          }).catch(err => {
            setLoading(false)
            Message.error('服务器连接异常')
          })
        } catch (e) {
          Message.error('请输入密码');
        }
      } catch (e) {
        Message.error('请输入账号');
      }
    }
    checkAccount();
  }
  // 加载动画
  const [loading, setLoading] = useState(false);
  return (
    <Spin dot loading={loading}>
      <div className="login_wrap">
        <div className="login_box">
          <h2>智慧停车管理系统</h2>

          {/* 主体 */}
          <Tabs defaultActiveTab='1'>
            <TabPane
              key='1'
              title={
                <span>
                  <IconPhone style={{ marginRight: 6 }} />
                  手机号登录
                </span>
              }
            >

              {/* ------------手机号登录------------------- */}

              <Typography.Paragraph style={style}>
                <Form form={form} style={{ width: 600 }}>
                  <FormItem
                    label='手机号'
                    field='phone'
                    required
                    rules={[
                      {
                        validator (value, cb) {
                          var pattern = /0?(13|14|15|18)[0-9]{9}/;
                          if (pattern.test(value) === false) {
                            return cb('请输入正确的手机号');
                          }
                          return cb();
                        },
                      },
                    ]}
                  >
                    <Input placeholder='手机号' onChange={(val) => { setPhone(val) }} />
                  </FormItem>
                  <FormItem
                    className='pwd'
                    label='验证码'
                    field='examCode'
                    required
                    rules={[
                      {
                        validator (value, cb) {
                          if (value !== 123) {
                            return cb('请输入验证码');
                          }
                          return cb();
                        },
                      },
                    ]}
                  >
                    <Input placeholder='验证码' onChange={(val) => { setCode(val) }} />
                    <input className='verificationCode' type="submit" value={codeNum} onClick={getCode.bind(this)} />
                  </FormItem>
                  <FormItem className="login">
                    <Button
                      type='primary'
                      style={{ marginRight: 24 }}
                      onClick={phoneLogin}
                    >
                      登录
                    </Button>
                  </FormItem>
                </Form>
              </Typography.Paragraph>
            </TabPane>
            <TabPane
              key='3'
              title={
                <span>
                  <IconUser style={{ marginRight: 6 }} />
                  密码登录
                </span>
              }
            >

              {/* --------账号密码登录------------------ */}

              <Typography.Paragraph style={style}>
                <Form form={form} style={{ width: 600 }}>
                  <FormItem
                    label='账号'
                    field='account'
                    required
                    rules={[
                      {
                        validator (value, cb) {
                          if (value == '' || value === undefined) {
                            return cb('请输入账号');
                          }
                          return cb();
                        },
                      },
                    ]}
                  >
                    <Input placeholder='账号' onChange={(val) => { setAccount(val) }} />
                  </FormItem>
                  <FormItem
                    label='密码'
                    field='pwd'
                    required
                    rules={[
                      {
                        validator (value, cb) {
                          if (value == '' || value === undefined) {
                            return cb('请输入密码');
                          }
                          return cb();
                        },
                      },
                    ]}
                  >
                    <Input.Password placeholder='密码' onChange={(val) => { setPassword(val) }} />
                  </FormItem>
                  <a href="#" className='forgetPwd'>忘记密码</a>
                  <FormItem className="login">
                    <Button
                      type='primary'
                      style={{ marginRight: 24 }}
                      onClick={accountLogin}
                    >
                      登录
                    </Button>
                  </FormItem>
                </Form>
              </Typography.Paragraph>
            </TabPane>
          </Tabs>
        </div>
      </div>
    </Spin>

  )
}
export default Login